/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.manager;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.requests.DirectEditRequest;
import org.eclipse.gef.tools.CellEditorLocator;
import org.eclipse.gef.tools.DirectEditManager;
import org.eclipse.swt.widgets.Text;
import org.eclipse.uml2.uml.Lifeline;

import com.cea.papyrus.diagram.sequence.sedi.edit.LifelineEditPart;
import com.cea.papyrus.diagram.sequence.sedi.edit.policy.LifelineLabelFormat;
import com.cea.papyrus.diagram.sequence.sedi.figures.LifelineFigure;

/**
 * Special DirectEditManager for Lifelines because it contains two editable
 * labels.
 * 
 * @author Andreas Limyr 
 * @author frankd@ifi.uio.no
 */
public class LifelineEditManager extends DirectEditManager {
	private int target;
	public LifelineEditManager(GraphicalEditPart source, Class<?> editorType, CellEditorLocator locator, int editTarget) {
		super(source, editorType, locator);
		this.target = editTarget;
	}
	
	@Override
	protected void bringDown() {
		((LifelineEditPart) getEditPart()).finishEditing();
	}

	@Override
	protected DirectEditRequest createDirectEditRequest() {
		DirectEditRequest request = super.createDirectEditRequest();

		// save the target type so that the correct command can be created later
		final Map<String, Object> extendedData = new HashMap<String, Object>();
		extendedData.put("target", new Integer(target));
		request.setExtendedData(extendedData);
		return request;
	}
	
	@Override
	protected void initCellEditor() {
		final LifelineEditPart lifelineEP = (LifelineEditPart) getEditPart();
		final Lifeline lifeline = lifelineEP.getUmlElement();
		
		final String initText;
		if (target == LifelineFigure.TARGET_REF) {
			String refLabel = LifelineLabelFormat.getDecomposedAsLabel(lifeline);
			initText = (refLabel != null) ? refLabel : "";
		}
		else initText = LifelineLabelFormat.getLabel(lifeline, true);

		getCellEditor().setValue(initText);
		Text text = (Text)getCellEditor().getControl();
		text.selectAll();
	}
}
